package adc.app.ui.wicket;

import org.apache.wicket.Component;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

public class LabeledLinkPanel extends Panel {

	private static final long serialVersionUID = 1L;
	
	private static final String ID_LINK = "lnk";
	private static final String ID_LABEL = "lbl";
	
	private AbstractLink link;
	private Component label;
	
	public LabeledLinkPanel(String id) {
		this(id, null);
		
	}
	
	public LabeledLinkPanel(String id, IModel<?> labelModel) {
		super(id, labelModel);
		add(link = new MockLink(getLinkId()));
		link.add(label = new Label(getLabelId(), labelModel));
		this.link.add(new AttributeAppender("title", true, new PropertyModel<Object>(this, "label.defaultModelObject"), " "));
	}
	
	public LabeledLinkPanel(String id, IModel<?> labelModel, AbstractLink link) {
		super(id, labelModel);
		if (!getLinkId().equals(link.getId())) {
			throw new WicketRuntimeException("The id for the link inside InvLabeledLinkPanel " 
					+ "must be InvLabeledLinkPanel.getLinkId()");
		}
		add(this.link = link);
		link.add(label = new Label(getLabelId(), labelModel));
		this.link.add(new AttributeAppender("title", true, new PropertyModel<Object>(this, "label.defaultModelObject"), " "));
	}
	
	public String getLinkId() {
		return ID_LINK;
	}
	
	public String getLabelId() {
		return ID_LABEL;
	}

	public final AbstractLink getLink() {
		return link;
	}

	public final LabeledLinkPanel setLink(AbstractLink link) {
		if (!getLinkId().equals(link.getId())) {
			throw new WicketRuntimeException("The id for the link inside InvLabeledLinkPanel " 
					+ "must be InvLabeledLinkPanel.getLinkId()");
		}
		this.link.replaceWith(link);
		this.link = link;
		this.link.addOrReplace(this.label);
		this.link.add(new AttributeAppender("title", true, new PropertyModel<Object>(this, "label.defaultModelObject"), " "));
		return this;
	}

	public final Component getLabel() {
		return label;
	}

	public final LabeledLinkPanel setLabel(Component label) {
		if (!getLabelId().equals(label.getId())) {
			throw new WicketRuntimeException("The id for the label inside InvLabeledLinkPanel " 
					+ "must be InvLabeledLinkPanel.getLabelId()");
		}
		this.link.replace(label);
		this.label = label;
		return this;
	}
	
	private static final class MockLink extends AbstractLink {

		private static final long serialVersionUID = 1L;

		private MockLink(String id) {
			super(id);
		}
		
	}
}
